package com.dyson.config;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author:DysonWy@Gmail.com
 * @time:2019/8/12 16:58
 */
@Component
@ServerEndpoint(value = "/websocket/{uid}")
public class MyWebSocket {
    private static Map<String, MyWebSocket> webSocketMap = new ConcurrentHashMap();
    private Session session;
    private String uid;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("uid") String uid, Session session) {
        this.session = session;
        this.uid = uid;
        webSocketMap.put(uid, this);
        sendMessage("链接到服务器");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketMap.remove(uid);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            System.out.println("socket,发送消息IO异常");
            e.printStackTrace();
        }
    }

    public void sendResultById(String uid) {
        MyWebSocket pcSocket = webSocketMap.get(uid);
        if (pcSocket != null) {
            pcSocket.sendMessage("videoAuth:true");
            pcSocket.onClose();
        }
    }
}
